/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.bastian.hinterleitner;

import java.util.ArrayList;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import de.bastian.hinterleitner.adaptersviews.StandardAdapter;
import de.bastian.hinterleitner.database.DataHelper;
import de.bastian.hinterleitner.tools.Category;
import de.bastian.hinterleitner.tools.Constants;
import de.bastian.hinterleitner.tools.DeleteTask;
import de.bastian.hinterleitner.tools.Entry;
import de.bastian.hinterleitner.tools.EntrySorter;
import de.bastian.hinterleitner.tools.WatchYourCashActivity;
import de.hijacksoft.wyc.R;

/**
 * 
 * @author basti
 */
public class Overview extends WatchYourCashActivity implements OnItemClickListener,
		OnItemLongClickListener {

	private ListView listview;
	StandardAdapter listAdapter;

	private static final String TAG = "WatchYourCash_Overview";

	private int year = -1;
	private int month = -1;
	private int day = -1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		if(Entry.sorting!=EntrySorter.SORT_BY_CATEGORY)Entry.sorting=EntrySorter.SORT_BY_DATE;
		if(icicle != null){
			year = icicle.getInt("year");
			month = icicle.getInt("month");
			day = icicle.getInt("day");
		}
		initGUI();
		refreshList();
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putInt("year", year);
		savedInstanceState.putInt("month", month);
		savedInstanceState.putInt("day", day);
	}

	private void initGUI() {
		setContentView(R.layout.activity_overview);
		listview = (ListView) findViewById(R.id.overview_list);
		listAdapter = new StandardAdapter(this, new ArrayList<Entry>());
		if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
			initHeader(listview);
		}else{
			initHeader(listview, ((LinearLayout)findViewById(R.id.overview_content)));
		}
		listview.setAdapter(listAdapter);
		listview.setOnItemClickListener(this);
		listview.setOnItemLongClickListener(this);
		initNav((LinearLayout) findViewById(R.id.overview_header), getString(R.string.overview));
        initFooter(((LinearLayout)findViewById(R.id.overview_layout_footer)));
        initLeftNavigation(((LinearLayout)findViewById(R.id.main_layout_overlay)));
	}

	private void refreshList() {
		new RefreshTask().execute();
	}

	private ArrayList<Entry> transform(ArrayList<Integer> ints) {
		DataHelper dh = DataHelper.getDataHelper(this);
		ArrayList<Entry> list = new ArrayList<Entry>();
		for (Integer n : ints) {
			String str = "" + n;
			double val = 0;
			if (year == -1) {
				for (Entry e : dh.getAllEntriesAt(n)) {
					val += e.getValueAs(getString(R.string.currency), this);
				}
			} else {
				if (month == -1) {
					for (Entry e : dh.getAllEntriesAt(year, n)) {
						val += e.getValueAs(getString(R.string.currency), this);
					}
					str = intToMonth(n);
				} else {
					if (day == -1) {
						for (Entry e : dh.getAllEntriesAt(year, month, n)) {
							val += e.getValueAs(getString(R.string.currency), this);
						}
					}
				}
			}
			list.add(new Entry(str, val, Constants.ID_NODATE));
		}
		return list;
	}

	public void onItemClick(AdapterView<?> av, View view, int i, long l) {
		i--; // because of header view
		if (listAdapter.getItem(i).getId() != Constants.ID_SEPERATOR) {
			if (listAdapter.getItem(i).getId() != Constants.ID_NODATE) {
				Intent intent = new Intent(this, NewEntry.class);
				intent.putExtra("itemId", "" + listAdapter.getItemId(i));
				startActivityForResult(intent, Constants.REQUEST_EDIT_ITEM);
			} else {
				if (year != -1) {
					month = monthToInt(listAdapter.getItem(i).getName());
				} else {
					year = Integer.parseInt(listAdapter.getItem(i).getName());
				}
				refreshList();
			}
		}
	}

	public boolean onItemLongClick(AdapterView<?> av, View view, int i, long l) {
		i--; // because of header-view
		if (listAdapter.getItemId(i) >= 0) {
			final int id = i;
			question(
					getString(R.string.deletequestion).replace("$1",
							listAdapter.getItem(id).getName()),
					getString(R.string.yes), getString(R.string.no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface di, int i) {
							DataHelper d = DataHelper
									.getDataHelper(Overview.this);
							d.delete((int) listAdapter.getItemId(id));
							refreshList();
						}
					}, null);
		}else if(listAdapter.getItemId(i) != Constants.ID_SEPERATOR){
			DataHelper dh = DataHelper.getDataHelper(Overview.this);
			final ArrayList<Entry> items = new ArrayList<Entry>();
			String which = "??";
			if(year != -1){
				which = listAdapter.getItem(i).getName()+" "+year;
				items.addAll(dh.getAllEntriesAt(year, monthToInt(listAdapter.getItem(i).getName())));
			}else{
				which = listAdapter.getItem(i).getName();
				items.addAll(dh.getAllEntriesAt(Integer.parseInt(listAdapter.getItem(i).getName())));
			}
			int count = items.size();
			question(getString(R.string.deletethese).replace("$1", ""+count).replace("$2", which),
					getString(R.string.yes),
					getString(R.string.no),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							new DeleteTask(Overview.this, items){
								@Override
								public void onFinish(boolean success) {
									refreshList();
								}
							}.execute();
						}
					},
					null);
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK)
			refreshList();
	}

	public void onNavEntryClicked(Button b) {
		setNavEntry(b.getText().toString());
		if (b.getText().equals("" + year)) {
			month = -1;
			day = -1;
			refreshList();
		} else if (b.getText().equals(intToMonth(month))) {
			day = -1;
			refreshList();
		} else {
			year = -1;
			month = -1;
			day = -1;
			refreshList();
		}
	}

	private ArrayList<Entry> addSeperators(ArrayList<Entry> list) {
		switch(Entry.sorting){
		
		case EntrySorter.SORT_BY_CATEGORY:
			Category cat = new Category(getString(R.string.uncategorized), null, -1);
			for(int i=0;i<list.size();i++){
				if(!list.get(i).getCategory().equals(cat)){
					cat = list.get(i).getCategory();
					double val = roundToDecimals(2, DataHelper.getDataHelper(this).getValueOfCategory(cat,list));
					Entry e = new Entry(cat+": "+val,val, Constants.ID_SEPERATOR);
					list.add(i,e);
				}
			}
			break;
			
		default:	
			int day = -1;
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getDay() != day) {
					Entry e = new Entry(list.get(i).getDay() + "."
							+ list.get(i).getMonth() + "." + list.get(i).getYear(),
							Double.MIN_VALUE, Constants.ID_SEPERATOR);
					e.setDate(list.get(i).getYear(), list.get(i).getMonth(), list
							.get(i).getDay());
					day = list.get(i).getDay();
					list.add(i, e);
				}
			}
		}
		
		return list;
	}

	public class RefreshTask extends AsyncTask<Integer, String, Integer> {

		ArrayList<Entry> list;

		@Override
		protected void onPreExecute() {
			setRequestedOrientation(getResources().getConfiguration().orientation);
			loading(true);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			setNavEntry(values[0]);
		}

		@Override
		protected Integer doInBackground(Integer... paramss) {
			DataHelper dh = DataHelper.getDataHelper(Overview.this);
			int sort = EntrySorter.SORT_BY_ID;
			list = new ArrayList<Entry>();
			if (year == -1) {
				ArrayList<Integer> years = dh.getAllYears();
				list = transform(years);
			} else {
				if (month == -1) {
					ArrayList<Integer> months = dh.getAllMonths(year);
					list = transform(months);
					publishProgress("" + year);
				} else {
					sort = Entry.sorting==EntrySorter.SORT_BY_CATEGORY?Entry.sorting:EntrySorter.SORT_BY_DATE;
					list = dh.getAllEntriesAt(year, month);
					publishProgress(intToMonth(month)+" "+year);
				}
			}
			list = EntrySorter.getSingleton(Overview.this).sortBy(list, sort);
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			loading(false);
			listAdapter.setItems(month == -1 ? list : addSeperators(list));
			listAdapter.notifyDataSetChanged();
			listview.setSelection(0);
			notifyHeader();
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
			if(month > -1){
				findViewById(R.id.layout_header_btn_options).setVisibility(View.VISIBLE);
			}else{
				findViewById(R.id.layout_header_btn_options).setVisibility(View.GONE);
			}
		}

	}
	
	@Override
	public boolean onCreatePopupMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_optionsmenu, menu);
		return super.onCreatePopupMenu(menu);
	}
	
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		try{
			if (month > -1)
				disableAllOptions(menu);
			if(Entry.sorting!=EntrySorter.SORT_BY_CATEGORY)menu.findItem(R.id.sort_by_category).setVisible(true);
			else menu.findItem(R.id.sort_by_date).setVisible(true);
		}catch(NullPointerException ex){
			ex.printStackTrace();
		}
		return super.onMenuOpened(featureId, menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.sort_by_date:
			Entry.sorting = EntrySorter.SORT_BY_DATE;
			refreshList();
			break;
		case R.id.sort_by_category:
			Entry.sorting = EntrySorter.SORT_BY_CATEGORY;
			refreshList();
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean hasOptionsMenu() {
		if(month > -1)return true;
		return false;
	}
}
